package cn.jinjimi.app.custom.ui.activity;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import cn.jinjimi.base.util.DateUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.controller.CustomerController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.custom.entity.Insurance;
import cn.jinjimi.app.custom.event.InsuranceDelEvent;
import cn.jinjimi.app.custom.event.InsuranceEvent;
import cn.jinjimi.app.custom.event.InsuranceUpdateEvent;
import cn.jinjimi.app.custom.event.InsureChangeEvent;
import cn.jinjimi.app.main.activity.WebActivity;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.dialog.DatePickerDialog;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.widget.LunarDatePicker;
import cn.jinjimi.app.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;

/**
 * 保单详情界面,修改保单,删除保单,发送续保提醒
 */
public class InsuranceEditActivity extends ToolBarCommonActivity implements TextWatcher {

    private TextView tvName;
    private EditText edName;
    private TextView tvDate;
    private TextView tvRemind;
    private TextView tvSend;
    private Calendar mInsuranceEffectDate = null;
    private DatePickerDialog mDateDialog = null;
    private int mDateType = DatePickerDialog.OnDateSetListener.TYPE_GREGORIAN_YEAR;

    private Insurance mInsureData;     //保单的全部数据，包括客户id，保单id，名称，生效日期，续费日期。

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_insurance_edit);
        setTitle(R.string.insure_info);
        setRightText(R.string.save);

        setRightBtnEnable(false);
        setSwipeEnabled(false);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        edName = (EditText) findViewById(R.id.ed_name);
        tvDate = (TextView) findViewById(R.id.tv_date);
        tvRemind = (TextView) findViewById(R.id.tv_remind);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvSend = (TextView) findViewById(R.id.txt_sendRenewRemind);
    }

    protected void initListener() {
        tvDate.setOnClickListener(this);
        edName.addTextChangedListener(this);
        tvDate.addTextChangedListener(this);
        tvSend.setOnClickListener(this);
        tvSend.setEnabled(false);
        findViewById(R.id.del_insurance).setOnClickListener(this);
    }

    private void initData() {
        String customId = getIntent().getStringExtra(BundleKey.PARAM_CUSTOM_ID);
        String policyId = getIntent().getStringExtra(BundleKey.PARAM_POLICY_ID);
        CustomerController.getInsureInfo(customId, policyId);
    }

    private void setData() {
        if (mInsureData.getDifference() == Insurance.PAYMENT_DATE) {
            tvRemind.setText(R.string.insure_today);
        } else {
            tvRemind.setText(mInsureData.getDifference() + "天后保险费到期");
        }
        tvName.setText(mInsureData.getName());
        tvDate.setText(DateUtils.formatYYYYMMDD(mInsureData.getEffect_date()));
        edName.setText(mInsureData.getName());
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.del_insurance:
                deleteInsureDialog();//弹出删除框
                break;
            case R.id.tv_date:
                showDatePickerDialog();//弹出日历控件
                break;
            case R.id.txt_sendRenewRemind:
                sendInsureRemind(mInsureData);
                break;
        }
    }

    @Override
    protected void rightAction() {
        super.rightAction();
        if (hasEdit())
            updateInsureInfo();//修改保单信息
    }

    /* 加载续费提醒的H5页面 */
    @EventTrace(EventID.APP_CUSTOMER_POLICY_SENDMSG)
    public void sendInsureRemind(Insurance insurance) {
        WebActivity.launch(InsuranceEditActivity.this, 1, insurance.getRemind_url(), getString(R.string.renew_remind));
    }

    /* 删除保单 */
    public void deleteInsureInfo() {
        ToastUtil.showLoading(InsuranceEditActivity.this, getString(R.string.deleting_wait));
        CustomerController.deleteInsureInfo(mInsureData.getCustomer_id(), mInsureData.getId());
    }

    /* 修改保单信息 */
    private void updateInsureInfo() {
        String insureNmae = edName.getText().toString().trim(); //保单名
        long effectTime;
        if (mInsuranceEffectDate != null) {
            effectTime = mInsuranceEffectDate.getTimeInMillis();
            if (mInsuranceEffectDate.after(Calendar.getInstance())) {
                ToastUtils.toastMessage(InsuranceEditActivity.this, getString(R.string.add_insurance_input_date_invalid));
                return;
            }
        } else {
            effectTime = mInsureData.getEffect_date();
        }
        if (StringUtils.isEmpty(insureNmae)) {
            ToastUtils.toastMessage(InsuranceEditActivity.this, "保单名不能为空");
            return;
        }
        CustomerController.updateInsureInfo(mInsureData.getCustomer_id(), effectTime, mInsureData.getId(), insureNmae, mInsureData.getTerm());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onInsuranceEvent(InsuranceEvent event) {
        switch (event.state) {
            case DataEvent.SUCC:
                mInsureData = event.data;
                tvSend.setEnabled(true);
                setData();
                break;
            case DataEvent.FAIL:
                break;
        }
    }

    /* 对保单删除事件进行监听 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onInsuranceDelEvent(InsuranceDelEvent event) {
        ToastUtil.hideLoading();
        if (event.state == InsuranceDelEvent.SUCC) {
            InsureChangeEvent insureChangeEvent = new InsureChangeEvent();
            insureChangeEvent.action = InsureChangeEvent.INSURE_DELETE;
            insureChangeEvent.insure = mInsureData;
            EventBus.getDefault().post(insureChangeEvent);
            ToastUtils.toastMessage(InsuranceEditActivity.this, getString(R.string.delete_insurance_success));//提示删除保单成功
            InsuranceEditActivity.this.finish();
        } else if (event.state == InsuranceDelEvent.FAIL) {
            ToastUtils.toastMessage(this, getString(R.string.delete_insurance_fail));                              //提示删除失败
        }
    }

    /* 对保单修改事件进行监听 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onInsuranceUpdateEvent(InsuranceUpdateEvent event) {
        if (event.state == InsuranceUpdateEvent.SUCC) {
            if (event.data != null) {
                mInsureData = event.data;
                InsureChangeEvent insureChangeEvent = new InsureChangeEvent();
                insureChangeEvent.action = InsureChangeEvent.ACTION_UPDATE;
                insureChangeEvent.insure = mInsureData;
                EventBus.getDefault().post(insureChangeEvent);
                ToastUtils.toastMessage(InsuranceEditActivity.this, getString(R.string.modify_success));//提示修改保单成功
                finish();
            }
        } else if (event.state == InsuranceUpdateEvent.FAIL) {
            ToastUtils.toastMessage(this, getString(R.string.update_insurance_fail));                              //提示修改失败
        }
    }

    /* 弹出确定框 */
    private void cancelEditAlert() {
        getAlertDialog().setTitle(getString(R.string.giveup_edit)).setMessage(getString(R.string.giveup_edit_msg)).setRightBtn(getString(R.string.ok), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAlertDialog().dismissDialog();
                finish();
            }
        });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    /*弹出删除框 */
    public void deleteInsureDialog() {
        getAlertDialog().setTitle(getString(R.string.insure_delete))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    @EventTrace(EventID.APP_CUSTOMER_POLICY_DELPOLICY)
                    public void onClick(View v) {
                        deleteInsureInfo();//删除
                        getAlertDialog().dismissDialog();
                    }
                });
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    /* 弹出日历控件 */
    private void showDatePickerDialog() {
        Calendar today = Calendar.getInstance();
        if (mInsuranceEffectDate != null) {
            today = mInsuranceEffectDate;
        } else if (mInsureData != null && mInsureData.getEffect_date() > 0) {
            today.setTimeInMillis(mInsureData.getEffect_date());
        }
        if (mDateDialog == null) {
            mDateDialog = new DatePickerDialog(InsuranceEditActivity.this, mDatelistener, mDateType, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH));
            mDateDialog.hideYearSwitchAndTypeSel();
        }
        mDateDialog.updateDate(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH), mDateType);
        mDateDialog.show();
    }

    private DatePickerDialog.OnDateSetListener mDatelistener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(LunarDatePicker view, Calendar date, String dateStr, int type) {
            mDateType = type;
            mInsuranceEffectDate = date;
            tvDate.setText(DateUtils.formatYYYYMMDD(mInsuranceEffectDate.getTimeInMillis()));
        }
    };

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    /* 对日期和保单名的文本监听 */
    @Override
    public void afterTextChanged(Editable s) {
        if (hasEdit()) {
            setRightBtnEnable(true);
        } else {
            setRightBtnEnable(false);
        }
    }

    @Override
    public void onBackPressed() {
        if (hasEdit()) {
            cancelEditAlert();
        } else {
            finish();
        }
    }

    /* 保单信息是否有修改 */
    public boolean hasEdit() {
        if (mInsureData == null)
            return false;
        if (!edName.isEnabled()) return false;
        String insureName = edName.getText().toString().trim();
        if (!mInsureData.getName().equals(insureName)) return true;
        String insureDate = tvDate.getText().toString().trim();
        String result = DateUtils.formatYYYYMMDD(mInsureData.getEffect_date());
        return !insureDate.equals(result);
    }
}